from flask import (
    Flask,
    render_template,
    request,
    redirect,
    url_for,
    send_from_directory,
)
import os
import uuid

app = Flask(__name__)

# 配置上传文件夹
UPLOAD_FOLDER = "uploads"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

# 确保上传目录存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


@app.route("/", methods=["GET", "POST"])
def upload_file():
    if request.method == "POST":
        # 检查请求中是否包含文件
        if "file" not in request.files:
            return redirect(request.url)

        file = request.files["file"]

        # 如果用户没有选择文件，浏览器也会提交一个没有文件名的空文件
        if file.filename == "":
            return redirect(request.url)

        # 生成唯一文件名以避免覆盖
        filename = str(uuid.uuid4()) + os.path.splitext(file.filename)[1]
        file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)

        # 保存文件
        file.save(file_path)

        # 获取文件大小
        file_size = os.path.getsize(file_path)

        # 转换文件大小为人类可读格式
        def format_size(size_bytes):
            for unit in ["B", "KB", "MB", "GB"]:
                if size_bytes < 1024.0:
                    return f"{size_bytes:.2f} {unit}"
                size_bytes /= 1024.0
            return f"{size_bytes:.2f} TB"

        human_readable_size = format_size(file_size)

        # 返回文件信息
        return render_template(
            "upload.html",
            message="文件上传成功!",
            file_info={
                "filename": file.filename,
                "size": human_readable_size,
                "path": file_path,
            },
        )

    return render_template("upload.html")


@app.route("/uploads/<filename>")
def download_file(filename):
    return send_from_directory(app.config["UPLOAD_FOLDER"], filename)


if __name__ == "__main__":
    app.run(debug=True)
